import { Injectable, OnInit } from "@angular/core";
import { Http } from "@angular/http";
import { CmHttp } from "./../../http-module/http.service";
import { Store } from "@ngrx/store";
import { sortFn } from "./utils";
import { Subject } from "rxjs/Subject";
import { Observable } from "rxjs/Observable";

import { TableParams } from "./quote-table.component";


import {
  getId,
  ADD_NEW_TABLE,
  SET_SORT,
  UPDATE_DATA,
  UPDATE_QUOTE
} from "./quote-table-state";

export interface TableState {
  tableState;
  originData;
  sortedData?;
  result?;
}

@Injectable()
export class QuoteTableService extends Subject<any>{
  id;
  originData;
  sortedData;
  currentState;

  constructor(private http: CmHttp, private tableState: Store<{ tableState }>) {
    super();
    //获取唯一ID
    let id = this.id = getId();
    //在整体状态树中增加表格状态实例，并含有ID，进行区分；
    tableState.dispatch({
      type: ADD_NEW_TABLE,
      payload: {
        id
      }
    });
    let testState = tableState.select("tableState");
    // console.debug("TestState: ", testState);
    //当表格状态仓库发生变化后，依据变化后状态进行数据排序，排序后传出数据数列
    tableState.subscribe(state => {
      // console.debug("ONCE STATE: ", state);
      let tableState = this.currentState = state.tableState.filter(table => table.id === id)[0];
      let originData = this.originData = tableState.originData;
      // let sortedData = this.sortedData = originData.sort(sortFn(tableState.sortBy, tableState.isReversed));
      // this.next(sortedData);
      this.next(originData);
    });
  }

  //传入表格参数，获取含有数据的Observable对象
  getDataByParams(params: TableParams) {
    if (params.method === "post") {
      return this.http.post(params.dataUrl, params.body).catch(err => {
        console.debug("Get Table Data Error: ", err);
        return Observable.from([{}]);
      })
    }
    return this.http.get(params.dataUrl).catch(err => {
      console.debug("Get Table Data Error: ", err);
      return Observable.from([{}]);
    });
  }

  //设置排序key
  setOrder(sortBy: string) {
    this.tableState.dispatch({
      type: SET_SORT,
      payload: {
        id: this.id,
        sortBy
      }
    });
  }

  //更新列表中的指定Quote，用于Socket及时更新
  updateQuote(quote) {
    this.tableState.dispatch({
      type: UPDATE_QUOTE,
      payload: {
        id: this.id,
        quote
      }
    });
  }


  //更新表格整体数据
  updateData(originData) {
    this.tableState.dispatch({
      type: UPDATE_DATA,
      payload: {
        id: this.id,
        originData
      }
    });
  }

}